import { mapState, mapGetters } from 'vuex'
import { getMousePos, getCompIdByParam } from '@/plugins/utils'
import { PAGE_TYPE } from '@/common/const'
import { COMPONENT_TYPES } from '@/common/const-wb'
import { postStatics } from '@/service/statics'
import { EventBus } from '@/store/index'
import { getMainListEventByEvents } from '@/store/utils'
import { H5_TYPE } from '@/common/const-dif'

class LoadExternalScript {
  static DYNAMICS_LOAD_SCRIPT  = {}
}
export const commonUtils = {
  data () {
    return {
      lists_: [],//这个代码很重要，不要删除，为了刷新web端ui,
    }
  },
  created () {
    const data_ = {
      mainControlId: '',
    };
    for(let key in data_) {
      this[key] = data_[key];
    }
    let events = this.item && this.item.events
    if(events){
      if(events.vote && events.reposts){
        if(events.reposts.index > events.vote.index){
          let repostsIndex = events.reposts.index
          let voteIndex = events.vote.index
          events.reposts.index = voteIndex
          events.vote.index = repostsIndex
        }
      }
      this.initSortEvent()
    }
  },
  computed: {
    ...mapGetters({
      globalCurrentPage: "getCurrentPage",
    }),
    ...mapState({
      pageIndex: state => state.pageIndex,
      statePopId: state => state.popId,
      allPages: state => state.allPages ? state.allPages : state.components.pages,
      controls: state => state.controls ? state.controls : state.wbComponents.controls,
      componentMap: state => state.componentMap ? state.componentMap : state.components.componentMap,
      pages: state => state.pages,
      pops: state => state.pops_,
      siteAttrs: state => state.attrs,
      siteInfo: state => state.siteInfo,
      interactionData: state => state.interactionData,
    }),
    isForm(){
      let isForm_ = false;
      if(this.globalCurrentPage){
        isForm_ = this.recursionSearchFormEvent(this.globalCurrentPage.components)
      }
      return isForm_;
    },
    wbListOrLists(){
      if(this.isWbLists){
        this.lists_ = this.wbLists
      }else{
        this.lists_ = this.lists
      }
      if(this.commonAttr.isFooter){
        this.lists_ =  _.slice(this.lists_, 0, this.commonAttr.itemNum);
      }
      return this.lists_
    },
    lists(){
      const relateAttrCompId = getCompIdByParam(this.commonAttr.relateAttrCompId);
      if(relateAttrCompId){
        const relateCompData = this.componentMap[relateAttrCompId];
        return relateCompData.lists;
      }else{
        return this.item.lists
      }
    },
    wbLists(){
      let wbLists_ = []
      const relateAttrCompId = getCompIdByParam(this.commonAttr.relateAttrCompId);
      let controlData;
      if(relateAttrCompId){
        const relateCompData = this.componentMap[relateAttrCompId];
        const relateMainEvent = getMainListEventByEvents(relateCompData.events);
        controlData = relateMainEvent && this.controls[relateAttrCompId] && this.controls[relateAttrCompId][relateMainEvent.controlId];
        if(controlData && controlData.data.elements){
          wbLists_ = controlData.data.oriElements || controlData.data.elements;
        }
      }else{
        let event = this.item && getMainListEventByEvents(this.item.events);
        if(event && this.getItemControls){
          controlData = this.getItemControls[event.controlId];
          if(controlData){
            if(controlData.data.elements){
              wbLists_ = controlData.data.elements;
            }
          }
        }
      }
      return wbLists_
    },
    isWbLists(){
      let wbLists_ = this.wbLists
      if(_.isArray(wbLists_) && wbLists_.length > 0){
        return true
      }else{
        return false
      }
    },
    commonAttr() {
      return this.item && this.item.commonAttr
    },
    sortedWbEvents(){
      let events = this.item && this.item.events
      let tempWbArr = [];
      _.forEach(events, (event) => {
        if(event.controlId && event.controlId.length > 0){
          tempWbArr.push(event)
        }
      })
      let sortedWbEvents_ = _.sortBy(tempWbArr, function(event) { return event.index })
      return sortedWbEvents_
    }
  },
  methods: {
    recursionSearchFormEvent(components){
      let isForm_ = false;
      _.forEach(components, (componentData) => {
        if(componentData.events.submit){
          isForm_ = true;
        }
        if(componentData.components && componentData.components.length > 0){
          isForm_ = this.recursionSearchFormEvent(componentData.components)
        }
      })
      return isForm_;
    },
    showPop(popId) {
      if(!this.pops[popId-1]){
        return
      }
      if (this.statePopId > 0 && this.statePopId != popId) {
        EventBus.$emit('closePop')
      }
      this.$store.commit('updatePopId', { popId })
      EventBus.$emit("showPop", { popId })
    },
    showPage(pageId) {
      if(!this.pages[pageId-1]){
        return
      }
      if (this.statePopId > 0) {
        EventBus.$emit('closePop')
      }

      EventBus.$emit("isStartHtml2canvas", { isStart: true, compId: this.item.id});
      let pageIndex = pageId - 1
      this.$store.commit('updatePageIndex', { pageIndex })

      EventBus.$emit('pauseVideo', { pageId })
      EventBus.$emit('playOrPauseAudio', { isPlay: false })
      if (this.siteAttrs.h5Type == H5_TYPE.mobile && !this.siteAttrs.isNoSwiping && this.siteAttrs.pageType == PAGE_TYPE.single) {
        EventBus.$emit("swiper", { pageId })
      } else {
        EventBus.$emit('showPage', { pageId })
      }
      this.$nextTick(() => {
        EventBus.$emit("isStartHtml2canvas", { isStart: false, compId: this.item.id});
      })
    },
    initSortEvent(){
    },
    getControlData(controlId) {
      try{
        return this.getItemControls[controlId]
      }catch(err){
        return {}
      }
    },
    onPostStatics(e, { comType, wModule, jumpUrl, params, apiUri }) {
      if (this.isH5Edit) {
        return
      }
      let xy = getMousePos(e)
      let comId
      if (this.item) {
        comId = this.item.id
      } else {
        comType = 'pageOrPop'
        comId = "pageId: " + this.pageId + "popId: " + this.popId
      }
      postStatics(this.$store.state, {
        comType, comId, wModule, pageIndex: this.pageIndex, apiType: "",
        apiUri: apiUri ? apiUri : "", params: params ? params : "", jumpUrl, clickSequence: "", mouseX: xy.x, mouseY: xy.y
      })
    },
    dynamicsLoadScript (url, attr, cb, groupId) {
      let this_ = this;
      let attrs = attr.split(".")
      let attr_ = ''
      if(attrs.length > 1){
        attr_ = attrs[0]
        if(window[attrs[0]] && window[attrs[0]][attrs[1]]){
          if(cb){
            cb(window[attr_]);
          }
          return;
        }
      }else{
        attr_ = attr
        if(window[attr]){
          if(cb){
            cb(window[attr_]);
          }
          return;
        }
      }
      let dynamicsScript = LoadExternalScript.DYNAMICS_LOAD_SCRIPT
      if(!dynamicsScript[attr]){
        dynamicsScript[attr] = { isLoading: false,  cbs: [], groupId}
      }
      if(dynamicsScript[attr].isLoading){
        if(cb){
          dynamicsScript[attr].cbs.push(cb)
        }
      }else{
        if(cb){
          dynamicsScript[attr].cbs.push(cb);
        }
        dynamicsScript[attr].isLoading = true;
        let script = document.createElement("script");
        script.type = "text/javascript";
        script.charset = "utf-8";
        script.src = url;
        script.onload = script.onreadystatechange = function() {
          if (
            !this.readyState || //这是FF的判断语句，因为ff下没有readyState这人值，IE的readyState肯定有值
            this.readyState == "loaded" ||
            this.readyState == "complete" // 这是IE的判断语句
          ) {
            let cbs;
            let groupId_ = dynamicsScript[attr].groupId;
            let groupObj = dynamicsScript[groupId_];
            let isCallback = false;
            if(groupId_){
              cbs = groupObj.cbs;
              groupObj.currentNum++;
              delete dynamicsScript[attr].groupId;
              if(groupObj.currentNum >= groupObj.totalNum){
                isCallback = true
              }else{
                if(!groupObj.isParallel){
                  let i = groupObj.currentNum;
                  let url_ = groupObj.urls[i];
                  let attr_ = groupObj.attrs[i];
                  let cb_ = groupObj.cbs[0];
                  this_.dynamicsLoadScript(url_, attr_, cb_, groupId_);
                }
              }
            }else{
              cbs = dynamicsScript[attr].cbs;
              isCallback = true
            }
            if(isCallback && cbs.length > 0){
              _.forEach(cbs, (cb) => {
                if(cb){
                  if(!window[attr]){
                    window[attr] = attr
                  }
                  cb(window[attr_]);
                }
              })
            }
          }
        };
        document.body.appendChild(script);
      }
    },
    injectDomInCompData(){
      this.item.vueContainer = this;
    },
    dynamicsLoadScripts (urls, attrs, cb, isParallel = true) {
      let groupId = attrs[0] + "_Group_Id_" +  _.random(0, 50);
      let dynamicsScript = LoadExternalScript.DYNAMICS_LOAD_SCRIPT;

      if(!dynamicsScript[groupId]){
        dynamicsScript[groupId] = { currentNum: 0, totalNum: urls.length, cbs: [cb], isParallel, urls, attrs }
      }
      
      for(let i = 0, len = urls.length; i < len; i++){
        let url = urls[i];
        let attr = attrs[i];
        if(isParallel){
          this.dynamicsLoadScript(url, attr, cb, groupId);
        }else{
          this.dynamicsLoadScript(url, attr, cb, groupId);
          break;
        }
      }
    },
    hasClass(elem, cls) {
      cls = cls || '';
      if (cls.replace(/\s/g, '').length == 0) return false; //当cls没有参数时，返回false
      return new RegExp(' ' + cls + ' ').test(' ' + elem.className + ' ');
    },
    addClass(elem, cls) {
      //HTML5新增classList
      //如果classList中存在给定的值，删除它，否则，添加它；
      if(elem.classList) elem.classList.add(cls);
    },
    removeClass(elem, cls) {
      if(elem.classList) elem.classList.remove(cls);
    },
  },
}
